package leetcode.editor.cn;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;

public class P438FindAllAnagramsInAString {
    public static void main(String[] args) {
        Solution solution = new P438FindAllAnagramsInAString().new Solution();
        System.out.println(solution.findAnagrams("cbaebabacd",
                "abc"));

    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        Map<Character, Integer> pMap = new HashMap<>();
        Map<Character, Integer> sMap = new HashMap<>();

        public List<Integer> findAnagrams(String s, String p) {
            List<Integer> result = new ArrayList<>();
            int left = 0, right = 0;
            char[] arr1 = p.toCharArray();
            int len = p.length();
            for (int i = 0; i < arr1.length; i++) {
                pMap.compute(arr1[i], (character, integer) -> integer == null ? 1 : integer + 1);
            }
            while (right < s.length()) {
                char c = s.charAt(right);
                right++;
                sMap.compute(c, (character, integer) -> integer == null ? 1 : integer + 1);
                if (right - left == len && sMap.equals(pMap)) {
                    result.add(left);
                }
                if (right - left == len) {
                    sMap.compute(s.charAt(left), (character, integer) -> integer == null || integer == 1 ? null : integer - 1);
                    left++;
                }

            }
            return result;
        }


    }
//leetcode submit region end(Prohibit modification and deletion)

}